#!usr/bin/node

const http = require('http'),
      db = require('./db.js');

http.createServer(async (req,res) => {
  console.log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  switch(req.method) {
    case 'GET':
      await select(req,res);
      break;
    case 'POST':
      insert(req,res);
      break;
    default:
      res.end('request method not support!');
  }

}).listen(8080);

async function select(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  const items = await db.getItems();
  res.end(JSON.stringify(items));
}

function insert(req,res) {
  res.setHeader('Access-Control-Allow-Origin','*');
  let item = '';
  req.on('data',chunk => {
    item += chunk;
  });
  req.on('end',async () => {
    if(item !== '' || typeof item !== 'undefined') {
      await db.insert(item);
      res.end('insert ok!');
    }else {
      res.end('item empty');
    }
  })
}
